<!--
  Checkbox 复选框组件                 zls-2023/07/31
    所有属性、事件、方法、插槽，请参考  https://vant-contrib.gitee.io/vant/#/zh-CN/checkbox
  
    Attributes
      1、list       多选框列表数据，格式为 [{ text: '复选框1', value: '1',disabled: false }]
    
    Demo
      <Form ref="formRef">
        <z-checkbox v-model="form.checkboxList" label="复选框回选" :list="checkboxList"></z-checkbox>
      </Form>

      const form = reactive({
        checkboxList: ['2']
      })

      const checkboxList = reactive([
        { text: '复选框1', value: '1' },
        { text: '复选框2', value: '2' },
        { text: '复选框3', value: '3' }
      ])
-->
<template>
  <z-input
    :label="$attrs['label']"
    :required="$attrs['required']"
    :border="$attrs['border']"
    :label-width="$attrs['label-width']"
    :rules="$attrs['required'] || $attrs['required'] === '' ? [{ required: true, message: '请选择' }] : []"
  >
    <template #input>
      <CheckboxGroup
        v-model="checkList"
        :disabled="$attrs['disabled']"
        :max="$attrs['max']"
        :direction="$attrs['direction'] || 'horizontal'"
        :icon-size="$attrs['icon-size']"
        :checked-color="$attrs['checked-color']"
        @change="change"
      >
        <Checkbox
          v-for="(item, i) in list"
          :key="i"
          :name="item.value"
          :disabled="item.disabled"
          :shape="$attrs['shape'] || 'square'"
          :label-disabled="$attrs['label-disabled']"
          :label-position="$attrs['label-position']"
          :bind-group="$attrs['bind-group']"
        >
          {{ item.text }}
        </Checkbox>
      </CheckboxGroup>
    </template>
    <template #right-icon>
      <z-svg name="chahao" v-if="checkList.length" @click.stop="clear"></z-svg>
    </template>
  </z-input>
</template>

<script>
export default { name: 'z-checkbox' }
</script>
<script setup>
import { ref, watch } from 'vue'
import { CheckboxGroup, Checkbox } from 'vant'
const emit = defineEmits(['update:modelValue'])

const props = defineProps({
  // {text:'',value:'',disabled:false}
  list: {
    type: Array,
    default: () => []
  },
  modelValue: {
    type: Array,
    default: () => null
  }
})

const checkList = ref([])

watch(
  () => props.modelValue,
  newVal => {
    checkList.value = newVal ?? []
  },
  { immediate: true }
)

function clear() {
  emit('update:modelValue', null)
}

function change(val) {
  emit('update:modelValue', val.length ? val : null)
}
</script>

<style lang="scss" scoped>
.van-checkbox {
  margin-bottom: 6px;
}
</style>
